package cn.itcast.bos.web.action;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.constants.Constants;
import cn.itcast.bos.domain.page.PageBean;
import cn.itcast.bos.domain.take_delivery.Promotion;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@SuppressWarnings("all")
public class PromotionAction extends BaseAction<Promotion>{
	//前台分页显示所有活动
	@Action(value="promotion_pageQuery",results={@Result(name="success",type="json")})
	public String promotionPageQuery(){
		//基于webservice,调用crm_management的方法
		PageBean pageBean = WebClient.create(Constants.BOS_MANAGEMENT_URL+"/services/PromotionService/pageQuery?page="+page+"&rows="+rows)
		.accept(MediaType.APPLICATION_JSON).get(PageBean.class);
		//存入值栈
		ActionContext.getContext().getValueStack().push(pageBean);
		return SUCCESS;
	}
	//显示具体活动详情
	@Action(value="promotion_showDetail")
	public String promotionShowDetail() throws IOException, TemplateException{
		//先判断id 对应的html页面是否存在,如果存在直接返回
		String htmlRealPath = ServletActionContext.getServletContext().getRealPath("/freemarker");
		File htmlFile = new File(htmlRealPath+"/"+model.getId()+".html");
		//不存在,查询数据库,结合freemarker生成网页模板
		if (!htmlFile.exists()) {
			//确定freemarker的版本
			Configuration configuration = new Configuration(Configuration.getVersion());
			//指定模板所需路径
			configuration.setDirectoryForTemplateLoading(new File("src\\main\\webapp\\WEB-INF\\template"));
			//确定模板文件
			Template template = configuration.getTemplate("promotion_detail.ftl");
			//模板默认编码
			configuration.setDefaultEncoding("utf-8");
			//通过webService动态查询数据
			Promotion promotion = WebClient.create(Constants.BOS_MANAGEMENT_URL+"/services/PromotionService/showDetail/"+model.getId())
			.accept(MediaType.APPLICATION_JSON).get(Promotion.class);
			Map<String, Object> root = new HashMap<>();
			root.put("promotion", promotion);
			//合并数据 utf-8
			template.process(root, new FileWriter(htmlFile));
		}
		//存在直接返回
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		FileUtils.copyFile(htmlFile, ServletActionContext.getResponse().getOutputStream());
		return NONE;
	}
	
	
}
